<template>
  <view class="place">
    <view class="box">
      <view class="line">
        <view class="title">运单单号</view>
        <view class="choose">
          <u-input
			:disabled="true"
            placeholder="自动生成"
            border="none"
            v-model="order_no"
            :customStyle="inputStyle"
          ></u-input>
          <!-- placeholderStyle="{'font-size': '28rpx';
        'color':' #999999'}" -->
        </view>
      </view>
      <view class="line" v-for="(item, index) in chooseList" :key="index">
        <view class="title"><text class="count">*</text>{{ item.name }}</view>
        <view class="choose">
          <u-cell-group :border="false" :customStyle="lineStyle">
            <u-cell
              :title="item.title"
              :isLink="true"
              :border="false"
              :titleStyle="item.titleStyle"
              :arrow-direction="item.direction"
              @click="chooseItem(item)"
            ></u-cell>
          </u-cell-group>
        </view>
      </view>
      <view class="line">
        <view class="title">选择地址</view>
        <view class="choose space-between">
          <u-cell-group :border="false" :customStyle="lineStyle" v-if="false">
            <u-cell
              :title="packageType.title"
              :isLink="true"
              :border="false"
              :titleStyle="packageType.titleStyle"
              @click="toPackagetype"
            >
              <u-image
                width="40rpx"
                height="40rpx"
                slot="right-icon"
                src="/static/icon/arrow.png"
              ></u-image>
            </u-cell>
          </u-cell-group>
          <view class="address row">
            <view class="aimg">
              <u-image
                width="40rpx"
                height="40rpx"
                src="/static/icon/set-address.png"
              ></u-image>
            </view>
            <view class="addressname" v-if="defaultAddress">
              <view class="name">
                <text>{{defaultAddress.real_name}}</text>
                <text class="phone">{{defaultAddress.phone}}</text>
              </view>
              <view class="adre">{{defaultAddress.detail}}</view>
            </view>
			<view class="addressname" v-else>
				选择地址
			</view>
          </view>
          <view class="aicon" @click="goAddressList">
            <u-image
              width="40rpx"
              height="40rpx"
              src="/static/icon/arrow.png"
            ></u-image>
          </view>
        </view>
      </view>
    </view>
    <view class="box" v-for="its in checkArrData">
      <view class="title">包裹信息</view>
      <view class="line lcolor">{{its.track}}</view>
      <view class="line">入库时间： {{its.warehousing_time}}</view>
      <view class="line">重量（kg）： {{its.weight}}</view>
      <view>物品： 
	  <!-- 生活用品/迪奥包包/*1 -->
		<text v-for="item in its.info">
		{{item.name}}{{item.brand?'/'+item.brand:''}}{{item.spe?'/'+item.spe:''}}{{item.num?'/'+item.num:''}}{{item.price?'/'+item.price:''}};</text>
	  </view>
    </view>
   <view class="box">
      <view class="info">
        <view
          class="ititle space-between"
          @click="goAddArticle"
        >
          <view class="it">物品信息</view>
          <view class="add">
            <view>添加物品</view>
            <view class="addIcon">
              <u-image
                width="40rpx"
                height="40rpx"
                src="/static/icon/add.png"
              ></u-image>
            </view>
          </view>
        </view>
       <view v-for="(item, index) in articleList" :key="index" :style="{ 'margin-top': index != 0 ? '60rpx' : '' }">
       	<view class="ititle space-between">
       		<view class="it iit">{{ item.title }}</view>
       		<view class="right">
       			<view class="add" @click="edit(item)">
       				<view class="addIcon">
       					<u-image width="30rpx" height="30rpx" src="/static/icon/edit.png"></u-image>
       				</view>
       				<view>编辑</view>
       			</view>
       			<view class="add" @click="deleted(item)">
       				<view class="addIcon">
       					<u-image width="30rpx" height="30rpx" src="/static/icon/delete.png"></u-image>
       				</view>
       				<view>删除</view>
       			</view>
       		</view>
       	</view>
       	<view class="detail space-between" v-for="(ditem, dindex) in item.detailList" :key="dindex">
       		<view>{{ ditem.specs }}</view>
       		<view>{{ ditem.count }}</view>
       	</view>
       </view>
      </view>
    </view>
    <view class="box">
      <view class="line">
        <view class="title">备注</view>
        <view class="choose">
          <u-input
            placeholder="备注信息"
            border="none"
            v-model="notesValue"
            :customStyle="inputStyle"
          ></u-input>
          <!-- placeholderStyle="{'font-size': '28rpx';
        'color':' #999999'}" -->
        </view>
      </view>
      <!-- <view class="serve">
        <view class="title">增值服务</view>
        <u-checkbox-group
          v-model="checkboxValue"
          placement="column"
          @change="checkboxChange"
        >
          <u-checkbox
            :customStyle="{ marginBottom: '8px' }"
            v-for="(item, index) in checkboxList"
            :key="index"
            :label="item.name"
            :name="item.id"
            labelColor="#999999"
          >
          </u-checkbox>
        </u-checkbox-group>
      </view> -->
	  <view class="line">
	    <view class="title">积分 <text style="font-size: 24rpx; color: #999;">(每笔订单最多可用30积分)</text> </view>
	    <view class="choose">
	      <u-input
	        placeholder="输入积分"
	        border="none"
	        v-model="integralValue"
	        :customStyle="inputStyle"
			type="number"
			:disabled="userInfos.integral==0"
	      ></u-input>
	      <!-- placeholderStyle="{'font-size': '28rpx';
	    'color':' #999999'}" -->
	    </view>
	  </view>
      <!-- <view class="line" v-for="(item, index) in integral" :key="index">
        <view class="title">{{ item.name }}</view>
        <view class="choose">
          <u-cell-group :border="false" :customStyle="lineStyle">
            <u-cell
              :title="item.title"
              :isLink="true"
              :border="false"
              :titleStyle="item.titleStyle"
              :arrow-direction="item.direction"
              @click="chooseItem(item)"
            ></u-cell>
          </u-cell-group>
        </view>
      </view> -->
      <view class="line">
        <view class="title">优惠券</view>
        <view class="choose space-between">
          <u-cell-group :border="false" :customStyle="lineStyle" v-if="false">
            <u-cell
              title="请选择优惠券"
              :isLink="true"
              :border="false"
              :titleStyle="packageType.titleStyle"
              @click="toPackagetype"
            >
              <u-image
                width="40rpx"
                height="40rpx"
                slot="right-icon"
                src="/static/icon/arrow.png"
              ></u-image>
            </u-cell>
          </u-cell-group>
          <view class="address row">
            <view class="addressname">
              <view class="name"> {{couponName?couponName:'选择优惠券'}} </view>
            </view>
          </view>
          <view class="aicon">
            <u-image
				@click="goCouponList"
              width="40rpx"
              height="40rpx"
              src="/static/icon/arrow.png"
            ></u-image>
          </view>
        </view>
      </view>
    </view>
    <view class="btn" @click="toDetail">确认发货</view>
    <!-- 选择列表 -->
    <u-picker
      :closeOnClickOverlay="true"
      :show="pickerShow"
      :columns="pickerColumns"
      :defaultIndex="defaultIndex"
      @confirm="confirm"
      @cancel="cancel"
    ></u-picker>
  </view>
</template>

<script>
export default {
  data() {
    return {
      // 包裹类型
      packageType: {
        title: "请选择包裹送达地址",
        titleStyle: {
          "font-size": "28rpx",
          color: "#999999",
        },
      },
      // 选择列表
      chooseList: [
        // {
        //   id: 0,
        //   name: "仓库",
        //   title: "请选择送达仓库",
        //   direction: "down",
        //   titleStyle: {
        //     "font-size": "28rpx",
        //     color: "#999999",
        //   },
        // },
        {
          id: 1,
          name: "运输路线",
          title: "请选择运输路线",
          direction: "down",
          titleStyle: {
            "font-size": "28rpx",
            color: "#999999",
          },
        },
      ],
      // 积分
      integral: [
        {
          id: 2,
          name: "积分",
          title: "请选择积分",
          direction: "down",
          titleStyle: {
            "font-size": "28rpx",
            color: "#999999",
          },
        },
      ],
	  integralValue:'',
      // 选择框样式
      lineStyle: {
        "background-color": "#F5F5F5",
        "border-radius": "5rpx",
        padding: "15rpx",
      },
      // 输入框样式
      inputStyle: {
        "background-color": "#F5F5F5",
        "border-radius": "5rpx",
        "padding-left": "43rpx",
        padding: "30rpx",
      },
      // 包裹单号
      order_no: "",
      // 多选
      checkboxValue: [],
      // 选择的索引
      chooseIndex: 0,
      // 选择展示
      pickerShow: false,
      // 备注信息
      notesValue: "",
      // 选择单项
      pickerColumns: [],
      // 默认选择的索引
      defaultIndex: [],
      country: ["中国深圳仓库1", "中国深圳仓库2", "中国深圳仓库3"],
      // 商品列表
      articleList: [],
      // 增值服务
      checkboxList: [
        {
          id: 0,
          name: "免费多件合箱",
        },
      ],
	  country:[],
	  line:[],
	  checkArrData:'',
	  w_id:190,	//仓库id
	  y_id:'',	//仓库id
	  defaultAddress:'',
	  couponName:'',	//优惠券名
	  couponId:'',		//优惠券id
	  userInfos:''		//用户信息
    };
  },
  onLoad(options){
	  if(options.checkArrData){
		  this.checkArrData = JSON.parse(options.checkArrData);
		  this.checkArrData.forEach(item=>{
			  item.info.forEach(its=>{
				  this.articleList.push({
					  title: its.name,
					  detailList: [
					    { specs: "数量", count: its.num },
					    { specs: "规格", count: its.spe },
					    { specs: "品牌", count: its.brand },
					    { specs: "单价", count: its.price },
					  ],
				  })
			  })
		  })
	  }
	  // 有地址传过来
	  if(options.form){
		  console.log(JSON.parse(options.form),"JSON.parse(options.form)");
		  for (let key in JSON.parse(options.form)) {
		  	this[key] = JSON.parse(options.form)[key];
		  }
	  }else{
		// 获取默认地址
		this.getDefaultAddress();
	  }
	  if (options.articleInfo) {
		let articleInfo = JSON.parse(options.articleInfo)
		if(articleInfo.index || articleInfo.index===0 ){
			this.articleList.splice(articleInfo.index,1,articleInfo);
		}else{
			this.articleList.push(articleInfo);
		}
	  }
	  console.log(this.checkArrData,"this.checkArrData 111")
	  // 获取仓库列表
	  this.getCountry();
	  // 获取路线
	  this.getLine();
	  // 获取用户信息
	  this.getUserInfos();
	  
  },
  methods: {
	  // 物品删除
	  deleted(ditem) {
	  	uni.showModal({
	  		title: "提示",
	  		content: "是否确认删除？",
	  		success: (res) => {
	  			if (res.confirm) {
	  				// 确定
	  				this.articleList.forEach((goods, index) => {
	  					if (goods.title == ditem.title) {
	  						this.articleList.splice(index, 1);
	  					}
	  				});
	  			} else if (res.cancel) {
	  				// 取消
	  				console.log("用户点击了取消");
	  			}
	  		},
	  	});
	  },
	  edit(item) {
	  	let form = {};
	  	form.checkArrData = this.checkArrData;
	  	form.w_id = this.w_id;
	  	form.y_id = this.y_id;
	  	form.chooseList = this.chooseList;
	  	form.integralValue = this.integralValue;
	  	form.notesValue = this.notesValue;
	  	form.couponId = this.couponId;
	  	form.couponName = this.couponName;
	  	form.articleList = this.articleList;
		form.defaultAddress = this.defaultAddress;
	  	form.url = "/pages/home/placeOrder";
		// let articleInfo = JSON.stringify(item);
		let articleInfo = ''
		this.articleList.forEach((goods, index) => {
			if (goods.title == item.title) {
				item.index = index;
				articleInfo = JSON.stringify(item);
				// this.articleList.splice(index, 1);
			}
		});
		this.$uniApi.to(`/pages/home/addArticle?articleInfo=${articleInfo}&form=${JSON.stringify(form)}`);
	  },
	  // 获取用户信息
	  getUserInfos(){
	  	this.$api.post({
	  		url: "/ebapi/user_api/get_my_user_info",
	  		data: {},
	  		success: (res) => {
	  			console.log(res,"res 用户信息")
	  			this.userInfos = res;
	  		},
	  	})
	  },
	  // 去添加商品
	  goAddArticle(){
	  	let form = {};
	  	form.checkArrData = this.checkArrData;
	  	form.w_id = this.w_id;
	  	form.y_id = this.y_id;
	  	form.chooseList = this.chooseList;
	  	form.integralValue = this.integralValue;
	  	form.notesValue = this.notesValue;
	  	form.couponId = this.couponId;
	  	form.couponName = this.couponName;
		form.articleList = this.articleList;
		form.defaultAddress = this.defaultAddress;
	  	form.url = "/pages/home/placeOrder"
	  	this.$uniApi.to(`/pages/home/addArticle?form=${JSON.stringify(form)}`);
	  },
	  getDefaultAddress(){
		  this.$api.post({
			  url: "/ebapi/user_api/user_default_address ",
			  // data: {},
			  success: (res) => {
				this.defaultAddress = res;
				console.log(res,"defaultAddress")
			  },
		   })
	  },
	  // 选择框选择
	  confirm(e) {
	  	console.log(e, "列表选项",this.chooseList);
	  	this.chooseList[0].title = e.value[0];
	  	this.chooseList[0].titleStyle = "#333333";
	  	this.pickerShow = false;
	  	if(this.chooseIndex == 0){
	  		this.w_id = this.country[e.indexs[0]].id
	  	}
		if(this.chooseIndex == 1){
			this.y_id = this.line[e.indexs[0]].id
		}
	  	this.chooseList.forEach((element) => {
	  		element.direction = "down";
	  	});
	  },
	  // 选择框取消
	cancel() {
		this.pickerShow = false;
		this.chooseList.forEach((element) => {
			element.direction = "down";
		});
	},
	getCountry(){
	  this.$api.post({
		  url: "/ebapi/public_api/america_warehouse",
		  // data: {},
		  success: (res) => {
			this.country = res;
			console.log(res,"country")
		},
	   })
	},
	getLine(){
		this.$api.post({
		    url: "/ebapi/public_api/transport_route",
		    // data: {},
		    success: (res) => {
				this.line = res;
				console.log(res,"line")
			},
		 })
	},
	goAddressList(){
		  let form = {};
		  form.checkArrData = this.checkArrData;
		  form.w_id = this.w_id;
		  form.y_id = this.y_id;
		  form.chooseList = this.chooseList;
		  form.integralValue = this.integralValue;
		  form.notesValue = this.notesValue;
		  form.couponId = this.couponId;
		  form.couponName = this.couponName;
		  form.articleList = this.articleList;
		  form.url = "/pages/home/placeOrder"
		  this.$uniApi.to(`/pages/my/myAddress?form=${JSON.stringify(form)}`);
	},
	goCouponList(){
		let form = {};
		form.checkArrData = this.checkArrData;
		form.w_id = this.w_id;
		form.y_id = this.y_id;
		form.chooseList = this.chooseList;
		form.integralValue = this.integralValue;
		form.notesValue = this.notesValue;
		form.defaultAddress = this.defaultAddress;
		form.articleList = this.articleList;
		this.$uniApi.to(`/pages/my/couponList?form=${JSON.stringify(form)}`);
		
	},
    // 确认发货
    toDetail() {
		// if(!this.w_id){
		// 	uni.showToast({
		// 		title:'请选择仓库！',
		// 		icon:"none"
		// 	})
		// 	return
		// }
		let that = this;
		if(!this.y_id){
			uni.showToast({
				title:'请选择路线！',
				icon:"none"
			})
			return
		}
		if(!this.defaultAddress.id){
			uni.showToast({
				title:'请选择地址！',
				icon:"none"
			})
			return
		}
		if(this.userInfos.integral<this.integralValue){
			uni.showToast({
				title:'积分不足！',
				icon:"none"
			})
			return
		}
		if(this.integralValue>30){
			uni.showToast({
				title:'每笔订单最多只可用30积分！',
				icon:"none"
			})
			return
		}
		let checkArrDataId = this.checkArrData.map(item=>item.id);
		let info = this.articleList.map(item=>{
			let obj = {};
			obj.name = item.title;
			obj.num = item.detailList&&item.detailList[0]&&item.detailList[0].count;
			obj.spe = item.detailList&&item.detailList[1]&&item.detailList[1].count;
			obj.brand = item.detailList&&item.detailList[2]&&item.detailList[2].count;
			obj.price = item.detailList&&item.detailList[3]&&item.detailList[3].count;
			return obj
		});
		let reqData = {
			f_ids:checkArrDataId.join(","),
			w_id:this.w_id,
			address_id:this.defaultAddress.id,
			y_id:this.y_id,
			use_integral:this.integralValue,
			remakes: this.notesValue,
			coupon_id:this.couponId,
			info:JSON.stringify(info)
		}
		wx.requestSubscribeMessage({
		  tmplIds: ['WkFtnGjHkbIb3xYscHD_SC0HmVe-jtbXaVBaEckiy3M'], // 此处可填写多个模板 ID，但低版本微信不兼容只能授权一个
		  success (res) {
			  uni.showLoading({
			    title: '提交中...',
			    mask: true // 是否显示透明蒙层，防止触摸穿透，默认为false
			  });
		    that.$api.post({
				url: "/ebapi/public_api/deliver_goods",
				data: reqData,
				success: (res) => {
					setTimeout(() => {
					  uni.hideLoading();
					  that.line = res;
					  that.$u.toast("下单成功！");
					  that.$uniApi.rl("/pages/my/waybill")
					  console.log(res,"line")
					}, 1000);
				},
				fail: (err) => {
					setTimeout(() => {
					  uni.hideLoading();
					}, 1000);
				}
		    })
		  }
		})
		
    },
    // 多选
    checkboxChange(n) {
      console.log("change", n);
    },
    // 点击选择项
    chooseItem(item) {
      this.pickerColumns = [];
      this.chooseIndex = item.id;
      if (item.direction == "down") {
        item.direction = "up";
        this.pickerShow = true;
        if (item.id == 0) {
		  let country = this.country.map(item=>item.info);
          this.pickerColumns.push(country);
        } else if (item.id == 1) {
		  let line = this.line.map(item=>item.info);
          this.pickerColumns.push(line);
        }
        if (item.titleStyle.color == "#999999") {
          this.defaultIndex = [];
        } else {
          this.defaultIndex.push(this.pickerColumns[0].indexOf(item.title));
        }
      } else {
        item.direction = "down";
      }
    },
  },
};
</script>

<style lang="scss">
.place {
  //   padding-bottom: 70rpx;

  .box {
    margin-top: 24rpx;
    padding: 36rpx 36rpx 45rpx;
    box-shadow: 0rpx 2rpx 10rpx 1rpx rgba(0, 0, 0, 0.08);
    border-radius: 16rpx;

    .line {
      margin-bottom: 34rpx;

      .title {
        font-size: $uni-text-size-title;
        margin-bottom: 20rpx;

        .count {
          color: #ff0000;
        }
      }

      .choose {
        .address {
          .aimg {
            width: 40rpx;
            height: 40rpx;
          }

          .addressname {
            margin-left: 30rpx;

            .name {
              font-size: $uni-text-size-title;
            }

            .phone {
              color: #999999;
              font-size: 24rpx;
              margin-left: 30rpx;
            }
          }
        }

        .aicon {
          width: 40rpx;
          height: 40rpx;
        }
      }
    }

    .info {
      .ititle {
        font-size: $uni-text-size-title;
        margin-bottom: 35rpx;
      }

      .add {
        color: $uni-color-main;
        display: flex;
        align-items: center;

        .addIcon {
          margin-left: 25rpx;
        }
      }
    }

    .serve {
      margin-bottom: 35rpx;

      .title {
        font-size: $uni-text-size-title;
        margin-bottom: 20rpx;
      }
    }

    .title {
      font-weight: bold;
      font-size: $uni-text-size-title;
      margin-bottom: 35rpx;
    }

    .line {
      margin-bottom: 35rpx;
    }

    .rightmargin {
      flex: 1;
    }

    .leftmargin {
      flex: 1;
    }

    .lcolor {
      color: $uni-color-main;
      font-size: $uni-text-size-title;
      font-weight: bold;
    }
  }

  .btn {
    text-align: center;
    color: #ffffff;
    font-size: 32rpx;
    padding: 33rpx 188rpx;
    border-radius: 50rpx;
    font-weight: bold;
    margin: 160rpx 15rpx 93rpx;
    background-color: $uni-color-main;
  }
}
</style>
